package test.day03;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class BinaryLevelOrderTree {
	public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
        }
	}

	public List<List<Integer>> levelOrder(TreeNode root) {
		if(root == null) {
			return new ArrayList<>();
		}
		List<List<Integer>> res = new ArrayList<>();
		Queue<TreeNode> queue = new LinkedList<>();
		queue.add(root);
		while(!queue.isEmpty()){
			int count = queue.size();
			List<Integer> list = new ArrayList<>();
			while(count > 0){
				TreeNode node = queue.poll();
				list.add(node.val);
				if(node.left != null) {
					queue.add(node.left);
				}
				if(node.right != null) {
					queue.add(node.right);
				}
				count--;
			}
			res.add(list);
		}
		return res;
	}


	List<List<Integer>> list = new ArrayList<>();
	public List<List<Integer>> levelOrder1(TreeNode root) {
		int level = 0;
		traversal(root, level);
		return list;
	}

	public void traversal(TreeNode node, int level) {
		if (node == null) {
			return;
		}
		if (list.size() <= level) {
			List<Integer> tmp = new ArrayList<>();
			tmp.add(node.val);
			list.add(tmp);
		} else {
			list.get(level).add(node.val);
		}
		traversal(node.left, level + 1);
		traversal(node.right, level + 1);
	}
}
